package com.qf.web.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.pojo.R;
import com.qf.pojo.ResultEnum;
import com.qf.pojo.User;
import com.qf.web.exs.BusinessException;
import com.utils.ThreadLocalUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    private ObjectMapper om = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("LoginInterceptor preHandle ...");

        //判断session中是否有用户的信息
        Object user = request.getSession().getAttribute("user");

        if (user == null){
            //没有登录 - 抛出异常
            throw new BusinessException(ResultEnum.NOLOGIN);
//            R r = R.error(ResultEnum.NOLOGIN);
//            String json = om.writeValueAsString(r);
//
//            response.setContentType("application/json;charset=utf-8");
//            response.getWriter().write(json);
//            return false;
        }

        //登陆了，我们将用户的uid存入ThreadLocal中
        ThreadLocalUtils.saveUid(((User)user).getId());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除uid和线程域对象的关系
        ThreadLocalUtils.removeUid();
    }
}
